// pages/profile/feedback.js
const app = getApp()
import api from '../../utils/api'

Page({
  data: {
    // 表单字段
    title: '',
    content: '',
    feedback_type: '',
    contact_phone: '',
    images: [], // 已上传图片URL

    // 选项
    typeOptions: [],

    // 控制
    canSubmit: false,
    submitting: false,
    uploading: false
  },

  onLoad() {
    this.loadTypes()
    // 预填手机号
    const phone = app?.globalData?.userInfo?.phone || ''
    if (phone) this.setData({ contact_phone: phone })
    this.updateCanSubmit()
  },

  async loadTypes() {
    try {
      const list = await api.feedback.getTypes()
      const types = (list || []).map(t => t.type)
      this.setData({ typeOptions: types })
    } catch (e) {
      // 默认类型兜底
      this.setData({ typeOptions: ['服务反馈', '展览反馈', '设施反馈'] })
    }
  },

  // 输入处理
  onInput(e) {
    const { field } = e.currentTarget.dataset
    this.setData({ [field]: e.detail.value })
    this.updateCanSubmit()
  },

  onTypeChange(e) {
    const idx = Number(e.detail.value)
    const type = this.data.typeOptions[idx] || ''
    this.setData({ feedback_type: type })
    this.updateCanSubmit()
  },

  // 选择并上传图片（临时复用头像上传接口）
  chooseImages() {
    const remain = 6 - this.data.images.length
    if (remain <= 0) return
    wx.chooseImage({
      count: remain,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: async (res) => {
        const files = res.tempFilePaths || []
        if (!files.length) return
        this.setData({ uploading: true })
        try {
          const uploaded = []
          for (const fp of files) {
            // 复用头像上传接口，取返回的full_url
            const r = await api.auth.uploadAvatar(fp)
            const url = r?.full_url || r?.avatar_url || ''
            if (url) uploaded.push(url)
          }
          this.setData({ images: [...this.data.images, ...uploaded] })
        } catch (err) {
          wx.showToast({ title: err.message || '图片上传失败', icon: 'none' })
        } finally {
          this.setData({ uploading: false })
          this.updateCanSubmit()
        }
      }
    })
  },

  removeImage(e) {
    const idx = Number(e.currentTarget.dataset.index)
    const list = this.data.images.slice()
    list.splice(idx, 1)
    this.setData({ images: list })
    this.updateCanSubmit()
  },

  previewImage(e) {
    const idx = Number(e.currentTarget.dataset.index)
    wx.previewImage({
      current: this.data.images[idx],
      urls: this.data.images
    })
  },

  isValidPhone(phone) {
    return /^1[3-9]\d{9}$/.test(String(phone || '').trim())
  },

  updateCanSubmit() {
    const { title, content, contact_phone } = this.data
    const titleOk = !!title && String(title).trim().length <= 100
    const contentOk = !!content && String(content).trim().length <= 2000
    const phoneOk = !contact_phone || this.isValidPhone(contact_phone)
    this.setData({ canSubmit: titleOk && contentOk && phoneOk })
  },

  async submit() {
    if (!this.data.canSubmit || this.data.submitting) return

    const ok = await app.checkAuth()
    if (!ok) return

    this.setData({ submitting: true })
    try {
      const payload = {
        title: this.data.title.trim(),
        content: this.data.content.trim(),
        feedback_type: this.data.feedback_type || undefined,
        contact_phone: this.data.contact_phone || undefined,
        images: this.data.images
      }

      await api.feedback.submit(payload)
      wx.showToast({ title: '提交成功', icon: 'success' })
      setTimeout(() => {
        wx.navigateTo({ url: '/pages/profile/my-feedback' })
      }, 600)
    } catch (err) {
      wx.showToast({ title: err.message || '提交失败', icon: 'none' })
    } finally {
      this.setData({ submitting: false })
    }
  },

  // 入口：我的反馈
  async goMyFeedback() {
    const ok = await app.checkAuth?.()
    if (!ok) return
    wx.navigateTo({ url: '/pages/profile/my-feedback' })
  }
})